<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 积分商城接口
 */
class Integral extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 商城
     * 
     */
    public function index()
    {
        $params = $this->request->post();
        $people = model('People')->people($params['openid']);
        if(isset($params['jf'])){//积分排序
            $status = $params['jf']=='true'?'integral desc':'integral asc';
        }elseif (isset($params['xl'])){//销量排序
            $status = $params['xl']=='true'?'sum desc':'sum asc';
        }else{
            $status = 'id desc';
        }
        $res = Db::name('integral')->where('integral','>',0)->whereTime('endtime','>',date('Y-m-d H:i:s',time()))->order($status)->select();
        return json_encode(array('res'=>$res,'people'=>$people));
    }
    public function detail(){
        $params = $this->request->post();
        $res = Db::name('integral')->where('id',$params['id'])->find();
        $people = model('People')->people($params['openid']);
        $status = Db::name('order')->where('goods_id',$params['id'])->where('status',3)->count();
        return json_encode(array('res'=>$res,'people'=>$people,'status'=>$status));
    }
    public function addorder(){
        $params = $this->request->post();
        $people = model('People')->people($params['openid']);
        $num = Db::name('integral')->where('id',$params['id'])->value('num');
        if($num <1){
            return 402;
        }
        $order_no = date('Ymd')."XTD".substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $arr = array(
            'people_id'     => $people['id'],
            'goods_id'      => $params['id'],
            'status'        => $params['status'],
            'num'           => $params['num'],
            'order_no'      => $order_no,
            'price'         => $params['price'],
            'bay'           => 2,
            'createtime'    => time()
        );
        $res = Db::name('order')->insert($arr);
        $id = Db::name('order')->getLastInsID();
        $this->get_qrcode($id);
        if($res){
            Db::name('people')->where('id',$people['id'])->setDec('over',$params['price']);
            return 200;
        }else{
            return 400;
        }

    }
    //微信端上传图片
    public function uploadimg()
    {
        $file = request()->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                $file = $info->getSaveName();
                $res = "/uploads/".$file;
                return $res;
            }
        }


    }
    public function ai(){
        $file = request()->file('file');
        $img = $this->uploadimg($file);
        require_once VENDOR_PATH . 'AI/AipOcr.php';
        // 定义常量
        $APP_ID = '16058795';
        $API_KEY = 'zvlUOqBtGW5qxvN55luHzgFu';
        $SECRET_KEY = '2uw4u8U4gkGuVLebecNpFbyyFXPjRyGc';
        $imgurl = "http://www.ymcnet.com/uploads/".$img;
        // 初始化
        $aipOcr = new \AipOcr($APP_ID, $API_KEY, $SECRET_KEY);
        $res = $aipOcr->basicGeneral (file_get_contents($imgurl));
        return json_encode($res['words_result']);
    }
    // 上传小票添加数据
    public function receipt(){
        $params = $this->request->post();
        $people = model('People')->people($params['openid']);
        $arr = array(
            'people_id'     => $people['id'],
            'image'         => $params['image'],
            'createtime'    => time()
        );
        $res = Db::name('receipt')->insert($arr);
        return $res?200:400;
    }
    // 我上传的小票列表
    public function receiptList(){
        $params = $this->request->post();
        $people = model('People')->people($params['openid']);
        $cartsD = Db::name('receipt')->where('people_id',$people['id'])->where('status',1)->select();
        foreach ($cartsD as $k=>$v){
            $cartsD[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $cartsY = Db::name('receipt')->where('people_id',$people['id'])->where('status',2)->select();
        foreach ($cartsY as $k=>$v){
            $cartsY[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $cartsW = Db::name('receipt')->where('people_id',$people['id'])->where('status',3)->select();
        foreach ($cartsW as $k=>$v){
            $cartsW[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        return json_encode(['cartsD'=>$cartsD,'cartsY'=>$cartsY,'cartsW'=>$cartsW]);
    }
    // 积分明细
    public function integralDetail(){
        $params = $this->request->post();
        $people = model('People')->people($params['openid']);
        $receipt = Db::name('receipt')->where('people_id',$people['id'])->where('status',2)->select();
        foreach ($receipt as $k=>$v){
            $receipt[$k]['name'] = '上传小票';
            $receipt[$k]['time'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        $order = Db::name('order')->where('people_id',$people['id'])->where('status',1)->select();
        foreach ($order as $k=>$v){
            $order[$k]['name'] = '兑换商品';
            $order[$k]['time'] = date('Y-m-d H:i:s',$v['createtime']);
        }
        return json_encode(['receipt'=>$receipt,'order'=>$order,'people'=>$people]);
    }
    public function mianfei(){
        $integral = Db::name('integral')->where('integral',0)->whereTime('endtime','>',date('Y-m-d H:i:s',time()))->select();
        return json_encode($integral);
    }



    //获取access_token
    public function get_access_token(){
        $appid = 'wx4e96723bd56676c3';
        $secret = '6b78f796bd45d534909c1bcc9d443875';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        return $this->curl_get($url);
    }

    public function curl_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $err?$err:$data;
    }
    //获得二维码
    public function get_qrcode($id) {
        $file = ROOT_PATH."log.txt";
//        header('content-type:image/gif');
//        header('content-type:image/png');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
        header('content-type:image/jpg');
        $path="pages/order/order?oid=".$id;
        $width=430;
        $data='{"path":"'.$path.'","width":'.$width.'}';
        $access = json_decode($this->get_access_token(),true);
        $content = "时间： ".date("Y-m-d H:i:s",time())."\r\n"."access_token： ".json_encode($access)."\r\n"."\r\n\r\n\r\n";
        file_put_contents($file, $content,FILE_APPEND);
        $access_token= $access['access_token'];
//        dump($data);exit;
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;
        $da = $this->get_http_array($url,$data);
        $name = time();
        $reslut = file_put_contents(ROOT_PATH . 'public' . DS . 'uploads/erweima/'.$name.'.jpg',$da);
        if($reslut){
            $ewm = '/uploads/erweima/'.$name.'.jpg';
            Db::name('order')->where('id',$id)->update(['ewm'=>$ewm]);
        }

        return $reslut?'uploads/erweima/'.$name.'.jpg':json_encode(400);
        //file_put_contents('./Uploads/qrcode/code-'.$name.'.jpg',$da);
        //这里强调显示二维码可以直接写该访问路径，同时也可以使用curl保存到本地，详细用法可以加群或者加我扣扣
    }
    public function get_http_array($url,$data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($ch);
        $error = curl_errno($ch);
        curl_close($ch);
        if ($error) {
            return $error;
        }else{
            return $tmpInfo;
        }
    }
}
